package com.fieldchain.ex.fa100.ui.kline;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;

import com.fieldchain.ex.fa100.R;
import com.fieldchain.ex.fa100.access.Constant;
import com.fieldchain.ex.fa100.base.MyBaseFragment;
import com.fieldchain.ex.fa100.inter.IntegerCallBack;
import com.fieldchain.ex.fa100.utils.chart.auxiliary.CoupleChartGestureListener;
import com.fieldchain.ex.fa100.utils.chart.auxiliary.CoupleChartValueSelectedListener;
import com.fieldchain.ex.fa100.utils.chart.inter.MyTouchListener;
import com.fieldchain.ex.fa100.utils.chart.mk_chart.MyCandleChart;
import com.fieldchain.ex.fa100.utils.chart.mk_chart.MyVolumChart;
import com.fieldchain.ex.fa100.utils.chart.mk_chart.MyZbChart;
import com.fieldchain.ex.fa100.utils.chart.test.DataTest;
import com.fieldchain.ex.fa100.utils.chart.utils.data.KlineIndex;
import com.fieldchain.ex.fa100.utils.net.access.HttpRequest;
import com.fieldchain.ex.fa100.utils.net.modle.StringListRequestTwo;
import com.fieldchain.ex.fa100.utils.share.ShareManager;
import com.github.mikephil.charting.charts.Chart;
import com.github.mikephil.charting.utils.Utils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/10/18
 */
public class KlineFragment extends MyBaseFragment implements View.OnClickListener, MyTouchListener.HighlightListener, IntegerCallBack {
    private TextView tvtime;
    private TextView tvOpen;
    private TextView tvHigh;
    private TextView tvLow;
    private TextView tvStatusclose;
    private TextView tvMa7;
    private TextView tvMa30;
    private RadioButton rzb0;
    private RadioButton rzb1;
    private RadioButton rzb2;
    private RadioButton rzb3;
    private RadioButton rzb4;
    private RadioButton rzb5;
    private RadioButton rzb6;
    private MyCandleChart candleChart;
    private MyVolumChart volumChart;
    private MyZbChart zbChart;


    private Timer timer;
    public static String tags = "";
    private int zbTag = 0;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
    private List<List<String>> mList = DataTest.getSimpleData();
    private String market = "";
    private int time;
    private boolean needData=true;


    private Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    getData();
                    break;
            }
        }
    };

    public static KlineFragment newInstance(String market, int time) {
        Bundle bundle = new Bundle();
        bundle.putString("market", market);
        bundle.putInt("time", time);
        KlineFragment fragment = new KlineFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void stop(){
        needData=false;
        HttpRequest.getInstance().clearAll();

        candleChart.clear();
        volumChart.clear();
        zbChart.clear();
    }
    @Override
    protected void findView() {
        tvtime = view.findViewById(R.id.tvtime);
        tvOpen = view.findViewById(R.id.tv_open);
        tvHigh = view.findViewById(R.id.tv_high);
        tvLow = view.findViewById(R.id.tv_low);
        tvStatusclose = view.findViewById(R.id.tv_statusclose);
        tvMa7 = view.findViewById(R.id.tv_ma7);
        tvMa30 = view.findViewById(R.id.tv_ma30);
        rzb0 = view.findViewById(R.id.rzb0);
        rzb1 = view.findViewById(R.id.rzb1);
        rzb2 = view.findViewById(R.id.rzb2);
        rzb3 = view.findViewById(R.id.rzb3);
        rzb4 = view.findViewById(R.id.rzb4);
        rzb5 = view.findViewById(R.id.rzb5);
        rzb6 = view.findViewById(R.id.rzb6);
        candleChart = view.findViewById(R.id.candle_chart);
        volumChart = view.findViewById(R.id.volum_chart);
        zbChart = view.findViewById(R.id.zb_chart);
    }

    @Override
    protected void setValue() {
        needProgress=false;
        market = getArguments().getString("market");
        time = getArguments().getInt("time");

        volumChart.setOnChartGestureListener(new CoupleChartGestureListener(volumChart, new Chart[]{candleChart, zbChart}) {
        });
        candleChart.setOnChartGestureListener(new CoupleChartGestureListener(candleChart, new Chart[]{volumChart, zbChart}) {
        });
        zbChart.setOnChartGestureListener(new CoupleChartGestureListener(zbChart, new Chart[]{candleChart, volumChart}) {
        });

        volumChart.setOnChartValueSelectedListener(new CoupleChartValueSelectedListener(volumChart, new Chart[]{candleChart, zbChart}, this));
        candleChart.setOnChartValueSelectedListener(new CoupleChartValueSelectedListener(candleChart, new Chart[]{volumChart, zbChart}, this));
        zbChart.setOnChartValueSelectedListener(new CoupleChartValueSelectedListener(zbChart, new Chart[]{candleChart, volumChart}, this));

        candleChart.setOnTouchListener(new MyTouchListener(candleChart, this, KlineIndex.kline));
        volumChart.setOnTouchListener(new MyTouchListener(volumChart, this, KlineIndex.volum1));
        zbChart.setOnTouchListener(new MyTouchListener(zbChart, this, KlineIndex.zbchart));


        setIndex(rzb0, 0);
        setIndex(rzb1, 1);
        setIndex(rzb2, 2);
        setIndex(rzb3, 3);
        setIndex(rzb4, 4);
        setIndex(rzb5, 5);
        setIndex(rzb6, 6);

        getData();
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_kline;
    }

    @Override
    public void onClick(View view) {

    }


    @Override
    public void enableHighlight() {
        candleChart.showHight();
        volumChart.showHight();
        zbChart.showHight();
    }

    @Override
    public void disableHighlight() {
        candleChart.hidnHight();
        volumChart.hidnHight();
        zbChart.hidnHight();
    }

    @Override
    public void index(int pos) {
        updateTv(pos);
    }

    public void updateTv(int index) {
        if(index<0)return;
        List<String> data = mList.get(index);
        long time = Long.parseLong(data.get(0)) ;
        float high = Float.parseFloat(data.get(1));
        float open = Float.parseFloat(data.get(2));
        float low = Float.parseFloat(data.get(3));
        float close = Float.parseFloat(data.get(4));
        float vol = Float.parseFloat(data.get(5));
        tvtime.setText(sdf.format(time));
        tvHigh.setText(m2(high));
        tvOpen.setText(m2(open));
        tvLow.setText(m2(low));
        tvStatusclose.setText(m2(close));

        tvMa7.setText(getMA(index, 7, mList) + "");
        tvMa30.setText(getMA(index, 30, mList) + "");
    }

    private String getMA(int index, int ma, List<List<String>> mList) {
        int count = 1;
        float sum = Float.parseFloat(mList.get(index).get(4));
        while (count < ma) {
            if (--index < 0) {
                break;
            }
            sum += Float.parseFloat(mList.get(index).get(4));
            count++;
        }
        return m2(sum / count);
    }

    public String m2(float f) {
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(f);
    }


    @Override
    public void onPause() {
        super.onPause();
        if (timer != null) {
            timer.cancel();
        }
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onResume() {
        super.onResume();
        startTimer();
    }

    private void startTimer() {
        if (timer != null) {
            timer = null;
        }
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(task, 0, 10000);
    }


    public void getData() {
        HashMap map = new HashMap();
        map.put("market", market);
        map.put("type", time + "");
        map.put("assist", ShareManager.getInstance().getCoinType());

        HttpRequest.getInstance().getRequest(map, Constant.kline, new StringListRequestTwo() {
            @Override
            public void onSucess(List<List<String>> list, int code, String msg) {
                if(needData) {
                    if (code == 200) {
                        mList.clear();
                        mList.addAll(list);
                        if (mList.size() > 0) {
                            if(zbTag==2){
                                candleChart.setValues(mList,2);
                            }else {
                                candleChart.setValues(mList,0);
                            }
//                            candleChart.setValues(mList,0);
                            volumChart.setValues(mList);
                            zbChart.setValues(mList, zbTag);
                            updateTv(mList.size() - 1);
                            setOffset();
                        }
                    }
                }
            }

            @Override
            public void onFaild(Exception e) {

            }
        });
    }


    public void setIndex(RadioButton rb, final int tag) {
        rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    boolean isTag=(zbTag==2);
                    zbTag = tag;
                    if(zbTag==2){
                        candleChart.setValues(mList,2);
                    }else if(isTag){
                        candleChart.setValues(mList,0);
                    }
                    zbChart.setValues(mList, tag);
                }
            }
        });
    }
    /*设置量表对齐*/
    private void setOffset() {
        float candleLeft = candleChart.getViewPortHandler().offsetLeft();
        float volumLeft = volumChart.getViewPortHandler().offsetLeft();
        float zbLeft = zbChart.getViewPortHandler().offsetLeft();


        float candleRight = candleChart.getViewPortHandler().offsetRight();
        float volumRight = volumChart.getViewPortHandler().offsetRight();
        float zbRight = zbChart.getViewPortHandler().offsetRight();


       float offsetLeft1 = Utils.convertPixelsToDp(candleLeft - volumLeft);
       float offsetLeft2=Utils.convertPixelsToDp(candleLeft - zbLeft);

       if(offsetLeft1!=0){
           volumChart.setExtraLeftOffset(offsetLeft1);
       }
        if(offsetLeft2!=0){
            zbChart.setExtraLeftOffset(offsetLeft2);
        }

        float offsetRight1 = Utils.convertPixelsToDp(candleRight - volumRight);
        float offsetRight2=Utils.convertPixelsToDp(candleRight - zbRight);


        if(offsetRight1!=0){
            volumChart.setExtraRightOffset(offsetLeft1);
        }
        if(offsetRight2!=0){
            zbChart.setExtraRightOffset(offsetLeft2);
        }
    }


}
